/**
 * 音频处理工具类
 */

/**
 * 将PCM数据转换为WAV格式
 * @param {ArrayBuffer} pcmData - PCM音频数据
 * @param {number} sampleRate - 采样率，默认16000
 * @param {number} channels - 声道数，默认1
 * @param {number} bitsPerSample - 每样本位数，默认16
 * @returns {ArrayBuffer} WAV格式的音频数据
 */
export function pcmToWav(pcmData, sampleRate = 16000, channels = 1, bitsPerSample = 16) {
  const bytesPerSample = bitsPerSample / 8
  const blockAlign = channels * bytesPerSample
  const byteRate = sampleRate * blockAlign
  const dataSize = pcmData.byteLength
  const fileSize = 44 + dataSize
  
  // 创建WAV文件头
  const buffer = new ArrayBuffer(fileSize)
  const view = new DataView(buffer)
  
  // RIFF标识符
  view.setUint32(0, 0x52494646, false) // "RIFF"
  view.setUint32(4, fileSize - 8, true) // 文件大小
  view.setUint32(8, 0x57415645, false) // "WAVE"
  
  // fmt子块
  view.setUint32(12, 0x666d7420, false) // "fmt "
  view.setUint32(16, 16, true) // Subchunk1Size
  view.setUint16(20, 1, true) // AudioFormat (PCM)
  view.setUint16(22, channels, true) // NumChannels
  view.setUint32(24, sampleRate, true) // SampleRate
  view.setUint32(28, byteRate, true) // ByteRate
  view.setUint16(32, blockAlign, true) // BlockAlign
  view.setUint16(34, bitsPerSample, true) // BitsPerSample
  
  // data子块
  view.setUint32(36, 0x64617461, false) // "data"
  view.setUint32(40, dataSize, true) // Subchunk2Size
  
  // 复制PCM数据
  const pcmView = new Uint8Array(pcmData)
  const wavView = new Uint8Array(buffer, 44)
  wavView.set(pcmView)
  
  return buffer
}

/**
 * 合并多个音频数据块
 * @param {Array<Uint8Array>} audioChunks - 音频数据块数组
 * @returns {Uint8Array} 合并后的音频数据
 */
export function mergeAudioChunks(audioChunks) {
  const totalLength = audioChunks.reduce((sum, chunk) => sum + chunk.length, 0)
  const mergedArray = new Uint8Array(totalLength)
  
  let offset = 0
  for (const chunk of audioChunks) {
    mergedArray.set(chunk, offset)
    offset += chunk.length
  }
  
  return mergedArray
}

/**
 * 创建音频Blob对象
 * @param {Uint8Array} audioData - 音频数据
 * @param {string} mimeType - MIME类型
 * @returns {Blob} 音频Blob对象
 */
export function createAudioBlob(audioData, mimeType = 'audio/wav') {
  return new Blob([audioData], { type: mimeType })
}

/**
 * 创建音频URL
 * @param {Blob} audioBlob - 音频Blob对象
 * @returns {string} 音频对象URL
 */
export function createAudioUrl(audioBlob) {
  return URL.createObjectURL(audioBlob)
}

/**
 * 下载音频文件
 * @param {string} audioUrl - 音频URL
 * @param {string} filename - 文件名
 */
export function downloadAudio(audioUrl, filename = `tts_${Date.now()}.wav`) {
  const link = document.createElement('a')
  link.href = audioUrl
  link.download = filename
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 播放音频
 * @param {HTMLAudioElement} audioElement - 音频元素
 * @returns {Promise} 播放Promise
 */
export function playAudio(audioElement) {
  return new Promise((resolve, reject) => {
    if (!audioElement) {
      reject(new Error('音频元素不存在'))
      return
    }
    
    audioElement.onended = resolve
    audioElement.onerror = reject
    audioElement.play().catch(reject)
  })
}

/**
 * 获取音频时长
 * @param {HTMLAudioElement} audioElement - 音频元素
 * @returns {number} 音频时长（秒）
 */
export function getAudioDuration(audioElement) {
  return audioElement ? audioElement.duration : 0
}

/**
 * 格式化时长显示
 * @param {number} seconds - 秒数
 * @returns {string} 格式化的时长字符串
 */
export function formatDuration(seconds) {
  if (!seconds || seconds < 0) return '00:00'
  
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

/**
 * 验证音频格式支持
 * @param {string} format - 音频格式
 * @returns {boolean} 是否支持
 */
export function isAudioFormatSupported(format) {
  const audio = document.createElement('audio')
  return audio.canPlayType(`audio/${format}`) !== ''
}

/**
 * 获取浏览器支持的音频格式
 * @returns {Array<string>} 支持的音频格式列表
 */
export function getSupportedAudioFormats() {
  const audio = document.createElement('audio')
  const formats = ['wav', 'mp3', 'ogg', 'webm', 'aac']
  
  return formats.filter(format => audio.canPlayType(`audio/${format}`) !== '')
} 